package ru.averta.notes.service.search;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.averta.notes.domain.Site;
import ru.averta.notes.service.security.SecurityService;
import ru.averta.notes.service.tag.TagManager;

import java.util.Collection;
import java.util.List;

/**
 * <code>SubjectCriteriaSearchServiceImpl</code>
 *
 * @author: fedor.belov (fedor.belov@mail.ru)
 * Date: 08.06.11 0:01
 */

@Service
public class SubjectCriteriaSearchServiceImpl implements SubjectCriteriaSearchService {

    @Autowired private SecurityService security;
    @Autowired private TagManager tagManager;
    @Autowired private SubjectCriteriaSearchDao criteriaDao;
    @Autowired private SubjectCriteriaSearchLucene criteriaLucene;

    @Override
    public List<Site> getCriteriaResult(SubjectCriteriaBean criteria) {
        if ("".equals(criteria.getFullText())) {
            Criteria hCriteria = criteriaDao.getHCriteriaBySubjectCriteria(criteria);
            return hCriteria.list();
        } else {
            Query query = criteriaLucene.getQueryBySubjectCriteria(criteria);
            return query.list();
        }
    }

    @Override
    public boolean checkSubjectByCriteria(Site subject, SubjectCriteriaBean criteria) {
        return (
                check_currentUser(subject, criteria) &&
                check_target(subject, criteria) &&
                check_other(subject, criteria)
                ) ? true : false;
    }

    private boolean check_currentUser(Site subject, SubjectCriteriaBean criteria) {
        return (subject.getUser().equals(security.getCurrentUser()));
    }

    private boolean check_target(Site subject, SubjectCriteriaBean criteria) {
        if (criteria.getTarget() == SubjectCriteriaBean.SubjectFilterTarget.Archive) {
            return subject.isArchived();
        } else {
            if (subject.isArchived()) return false;
        }

        if (criteria.getTarget() == SubjectCriteriaBean.SubjectFilterTarget.All) {
            return true;
        } else if (criteria.getTarget() == SubjectCriteriaBean.SubjectFilterTarget.Inbox) {
            return false; //TODO
        } else {
            return false;
        }
    }

    private boolean check_other(Site subject, SubjectCriteriaBean criteria) {
        if (criteria.isFilterFavorite()) {
            if (!subject.isFavorite()) return false;
        }

        Collection<String> filterTags = criteria.getFilterTags();
        if (filterTags != null) {
            for (String tag : filterTags) {
                if (!tagManager.hasTag(subject, tag)) return false;
            }
        }

        return true;
    }
}
